<template>
  <div class="el-input-pwd">
    <div class="input-pwd-list">
      <el-input
        class="input-pwd"
        v-for="(item, index) in inputList"
        v-model="valContent[item]"
        type="password"
        ref="inputListRef"
        :key="item"
        @keyup.stop="($event) => loseBlur($event, index, item)"
        maxlength="1"
      >
      </el-input>
    </div>
    <div class="msg-item error" v-if="errorInfo">
      {{ errorInfo }}
    </div>
    <div class="msg-item" v-else-if="info">
      {{ info }}
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, computed, watch } from 'vue'
// const emits = defineEmits([''])

const props = defineProps({
  length: {
    type: Number,
    default: 6
  },
  value: {
    type: String,
    default: ''
  },
  info: {
    type: String,
    default: ''
  },
  errorInfo: {
    type: String,
    default: ''
  }
})

const emits = defineEmits(['update:value'])

// 保存输入框
const inputList = reactive([])
// 存储数据
const valContent = reactive({})
// 绑定的ref
const inputListRef = ref(null)
// 当前的输入内容
const currentInput = computed(() => Object.values(valContent).join(''))

const initData = () => {
  for (let i = 0; i < props.length; i++) {
    const key = `input-pwd-${i}`
    valContent[key] = props.value[i] || ''
    inputList.push(key)
  }
}

const loseBlur = (evt, i, key) => {
  if (evt.code === 'Backspace') {
    goFocus(i, 'fornt')
  } else {
    if (i === inputList.length - 1) {
      return
    }
    goFocus(i, 'next')
  }
}

const goFocus = (i, type) => {
  if (!inputListRef.value) {
    return
  }
  if (inputListRef.value instanceof Array) {
    inputListRef.value[i].blur()
    if (type === 'next' && i < inputList.length) {
      inputListRef.value[i + 1].focus()
    }
    if (type === 'fornt' && i > 0) {
      inputListRef.value[i - 1].focus()
    }
  } else {
    inputListRef.value[i].blur()
  }
}

initData()

watch(currentInput, (val) => {
  emits('update:value', val)
})

watch(() => props.value, (val) => {
  for (let i = 0; i < props.length; i++) {
    const key = `input-pwd-${i}`
    valContent[key] = props.value[i] || ''
  }
})

</script>

<style lang="less" scoped>
.el-input-pwd {
  width: 100%;
  padding: 10px 15px;
  overflow: hidden;
  .input-pwd-list {
    height: 40px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    &:deep(.el-input) {
      width: 40px;
      margin: 0 5px;
      .el-input__inner {
        text-align: center;
      }
    }
  }
  .msg-item{
    height: 25px;
    text-align: center;
    color: #999;
    font-size: 12px;
    margin-top: 10px;
    line-height: 25px;
    &.error{
      color: var(--van-danger-color);
    }
  }
}
</style>
